package de.fhk.fst.dvr.recording

import static de.fhk.fst.dvr.recordings.RequestStatus.*
import de.fhk.fst.dvr.BaseController
import de.fhk.fst.dvr.recordings.RequestStatus

class RecordingRequestController extends BaseController {

  def scaffold = true

  def save = {
    RecordingRequest request = new RecordingRequest(params)
    request.requester = session.user
    if (!session.admin) {
      request.status = PENDING
    } else {
      request.status = GRANTED
    }
    if (request.save()) {
      redirect(view:"list")
    } else {
      redirect(view:"create")
    }
  }

  def showPending = {
    renderRequestList(findRequests(PENDING))
  }

  def showGranted = {
    renderRequestList(findRequests(GRANTED))
  }

  def showDenied = {
    renderRequestList(findRequests(DENIED))
  }

  private List<RecordingRequest> findRequests(RequestStatus status) {
    return RecordingRequest.findAllByStatusAndRequester(status, session.user)
  }

  protected renderRequestList(List<RecordingRequest> requests) {
    render(view: "list", model: [recordingRequestInstanceList: requests, recordingRequestInstanceTotal: resultCount(requests)])
  }

  private <T> int resultCount(List<T> result) {
    return (result == null) ? 0 : result.size()
  }
}
